import './index.scss';

import { json } from '@codemirror/lang-json';
import CodeMirror, { Compartment } from '@uiw/react-codemirror/esm';

interface CodeMirrorJSONProps {
    code: string;
}

export interface CodeMirrorJSONRef {
    getData: () => void;
}

export const CodeMirrorJSON = memo(
    forwardRef<CodeMirrorJSONRef, CodeMirrorJSONProps>((props, ref) => {
        const [codeVal, setCodeVal] = useState<string>('');
        // json
        const jsonLang = new Compartment().of(json());

        useEffect(() => {
            if(props.code) {
                setCodeVal(JSON.stringify(props.code, null, '\t'));
            }
        }, [props.code]);

        useImperativeHandle(ref, () => ({
            getData: () => { // 获取数据
                const str = codeVal?.toString();
                return str;
            },
        }));

        return (
            <div id="apiJsonCode" className="w-full h-120" style={{ overflow: 'auto', border: '1px solid #e8eaf0' }}>
                <CodeMirror
                    value={codeVal}
                    onChange={(value) => {
                        setCodeVal(value);
                    }}
                    extensions={[jsonLang]}
                    style={{ border: '1px solid #e8eaf0' }}
                    className="w-full h-120"
                />
            </div>
        );
    })
);
